package com.eu.ebpm.engine.cmd.pvm;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eu.ebpm.engine.cmd.TaskIdentitySupport;
import com.eu.ebpm.engine.entity.deploy.Mission;
import com.eu.ebpm.engine.entity.enumm.TaskStatus;
import com.eu.ebpm.engine.entity.history.HisTask;
import com.eu.ebpm.engine.entity.runtime.TaskEntity;
import com.eu.ebpm.engine.repository.ExecutionRepository;
import com.eu.ebpm.engine.repository.HisTaskRepository;
import com.eu.ebpm.engine.repository.TaskRepository;
import com.eu.ebpm.engine.script.SpelScriptService;
import org.springframework.util.StringUtils;

/**
 * @author 王晓华
 */
@Component
public class UserTaskIntoCommand {

	@Autowired
	protected TaskIdentitySupport taskIdentityService;

	@Autowired
	private TaskRepository taskRepository;
	
	@Autowired
	private HisTaskRepository hisTaskRepository;

	@Autowired
	private ExecutionRepository executionRepository;
	
	@Autowired
	private SpelScriptService spelScriptService;

	public void execute(Mission m, TaskEntity task, Map<String, Object> variables) {

		task.initId();
		task.setName(m.getName());
		task.setDesc(m.getDesc());
		task.setCreateTime(new Date());
		task.setMissionId(m.getId());
		task.setAssigneeTime(new Date());

		if (!StringUtils.isEmpty(m.getAssignee())) {

			spelScriptService.initAssignee(m, task);

		} else {
			// 2、上个节点非开始节点，则设置assignee为null，否则，设置为executionUser
			if (!m.isStartEventTargetRef()) {
				task.setAssignee(null);
				task.setAssigneeTime(null);
			} else {
				String assignee = executionRepository.queryById(task.getExecutionId()).getUser();
				if (assignee != null) {
					task.setAssignee(assignee);
				}
			}
		}

		taskRepository.insert(task);
		
		hisTaskRepository.insert(new HisTask(task.getId(), m.getType(), m.getName(), m.getDesc(), null, task.getExecutionId(), task.getRootExecutionId(), task.getMissionId(), task.getAssignee(), task
				.getAssigneeTime(), task.getCreateTime(), null, null, TaskStatus.EXEING.getCode()));

		taskIdentityService.insertTaskCandidate(m, task);

	}

}
